package com.csf.client;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import com.csf.client.message.TestMessage.Test;
import com.csf.client.pipeline.PipeLineFactory;

public class Client {

	public static void main(String[] args) throws Exception {
		String host =  "127.0.0.1"; 
		
		//String host = "localhost";
		int port = Integer.parseInt("8080");
		ChannelFactory factory = new NioClientSocketChannelFactory(Executors
				.newCachedThreadPool(), Executors.newCachedThreadPool());
		ClientBootstrap bootstrap = new ClientBootstrap(factory);
		bootstrap.setPipelineFactory(new PipeLineFactory());
		bootstrap.setOption("tcpNoDelay", true);
		bootstrap.setOption("keepAlive", true);
		ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
				port));

		// Wait until the connection attempt succeeds or fails.
		          Channel channel = future.awaitUninterruptibly().getChannel();
		          if (!future.isSuccess()) {
		              future.getCause().printStackTrace();
		              bootstrap.releaseExternalResources();
		              return;
		          }

		
//		System.out.println("Sending message 1");
//		channel.write(new TestMessage(999, "sudheer"));
//		System.out.println("Sending message 2");
//		channel.write(new TestMessage(1000, "sunil"));
		       
  		System.out.println("Sending message from CLient to Server:");
  		channel.write(Test.newBuilder().setId(9).setName("suji").build().toByteArray());
          
		          
		          
		//TODO - Client still waiting for server need to free resources
		future.getChannel().getCloseFuture().awaitUninterruptibly();
		factory.releaseExternalResources();
		
		
	}
	
}
